package com.lingyuan.warehouse.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.lingyuan.common.core.domain.vo.call.WareCall;
import com.lingyuan.common.core.domain.vo.call.WmsConstant;
import com.lingyuan.common.core.domain.warehouse.pojo.PO.WmsPurchaseDetail;
import com.lingyuan.common.core.exception.GlobalException;
import com.lingyuan.warehouse.config.Constant;
import com.lingyuan.warehouse.config.RedisConssion;
import com.lingyuan.warehouse.domain.WmsPurchase;
import com.lingyuan.warehouse.domain.WmsWarePO;
import com.lingyuan.warehouse.domain.WmsWareSkuPO;
import com.lingyuan.warehouse.mapper.WareMapper;
import com.lingyuan.common.core.domain.vo.wms.WmsWareSkuVO;
import com.lingyuan.warehouse.service.WareService;
import lombok.extern.log4j.Log4j2;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author：寇可往，我亦可往。
 * @Package：com.lingyuan.service.impl
 * @Project：lingyuan-shopping-mall
 * @name：WareServiceimpl
 * @Date：2024/9/18 10:13
 */
@Service
@Log4j2
public class WareServiceimpl extends ServiceImpl<WareMapper , WmsWareSkuPO> implements WareService {

    @Autowired
    private WareMapper wareMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedisConssion redisConssion;

    @Autowired
    private WmsPurchaseDetailServiceimpl wmsPurchaseDetailServiceimpl;

      /**
     * DOTO 用户；列表预警
     */
    @Override
    public List<WmsWareSkuVO> getWareSkuList(String skuName, Integer userId) {
        ArrayList<WmsWareSkuVO> list = new ArrayList<> ();
        ArrayList<WmsWareSkuVO> list1 = new ArrayList<> ();
        List<WmsWareSkuVO> wareSkuList=null;
        Boolean hasKey = redisTemplate.hasKey ( Constant.WARE_LOCK_KEY );
        // 从redis中获取数据
            if(hasKey){
                List<String> range = redisTemplate.opsForList()
                        .range(Constant.WARE_LOCK_KEY, 0, -1);
                wareSkuList = JSON.parseArray ( range.toString (), WmsWareSkuVO.class );
            }else {
                wareSkuList = wareMapper.getWareSkuList ();
            }
            if (wareSkuList != null){
                for (WmsWareSkuVO wmsWareSkuVO : wareSkuList) {
                    if (skuName != null && wmsWareSkuVO.getSkuName ().contains ( skuName ) &&
                     userId != null && Long.valueOf ( userId ).equals ( wmsWareSkuVO.getUserId ())) {
                        list.add ( wmsWareSkuVO );
                    }else if(Long.valueOf ( userId ).equals ( wmsWareSkuVO.getUserId () )) {
                        list1.add ( wmsWareSkuVO );
                    }
                }
            }
             return skuName != null ? list1 : list;
    }
    @Override
    public void wareAdd(WmsWareSkuPO skuName) {
         wareMapper.wareAdd(skuName);
         redisConssion.initWareSku ();
    }


    @Override
    public void mergePurchase(List<WmsWareSkuVO> wareSkuList) {
        wareMapper.mergePurchase(wareSkuList);
        redisConssion.initWareSku ();
    }
    @Override
    public void wareLock(List<WareCall> wareSkuList) {
        if (wareSkuList.size ()==0){
            throw new GlobalException ( "不可为null" );
        }
        wareSkuList.stream().forEach(wareSku->{
            Integer stock = Integer.valueOf(redisTemplate.boundHashOps(WmsConstant.WARE_LOCK_KEY_VALUE).get(wareSku.getId()).toString());
            Integer nowStock = Math.toIntExact(stock - wareSku.getStock());
            log.info("商品:{},扣减后库存:{}",wareSku.getId(),nowStock);
            redisTemplate
                    .boundHashOps(WmsConstant.WARE_LOCK_KEY_VALUE)
                    .put (String.valueOf(wareSku.getId()),nowStock.toString());
        });
    }

    @Override
    public List<WmsWareSkuVO> fandAll() {
        return wareMapper.fandAll ();
    }

    @Override
    @Transactional
    public void wareByIdAdd(WmsWareSkuPO wmsWareSkuPO) {
        //添加订单表
        WmsPurchase wmsPurchase = new WmsPurchase ();

        wmsPurchase.setStatus (Constant.WARS_PURCHASE_DETAIL_KEY );
        //数量
        wmsPurchase.setSkuNum ( wmsWareSkuPO.getStock () );
        //sku名称
        wmsPurchase.setSkuName ( wmsWareSkuPO.getSkuName () );
        //买入金额
        wmsPurchase.setAmount ( wmsWareSkuPO.getAmount () );
        wmsPurchase.setPriority ( wmsWareSkuPO.getPriority () );
        wmsPurchase.setCreateTime ( String.valueOf ( new java.util.Date () ) );
        // 更新日期
        wmsPurchase.setUpdateTime ( String.valueOf ( new java.util.Date () ) );
        wareMapper.purchaseAdd ( wmsPurchase );
        //查看仓库Id
        WmsWareSkuPO wareName = wareMapper.getWareName (wmsWareSkuPO.getSkuId ());
        if (wareName == null){throw new RuntimeException ("商品不存在");}
        WmsPurchaseDetail wmsPurchaseDetail = new WmsPurchaseDetail ();
        wmsPurchaseDetail.setStatus ( Constant.WARS_PURCHASE_DETAIL_KEY );
        wmsPurchaseDetail.setSkuId ( wareName.getSkuId () );
        wmsPurchaseDetail.setSkuNum ( wmsWareSkuPO.getStock () );
        wmsPurchaseDetail.setPurchaseId ( wmsPurchase.getId () );
        wmsPurchaseDetail.setSkuPrice ( wmsWareSkuPO.getAmount () );
        //添加详情表
        wareMapper.wareWmsPurchaseDetail ( wmsPurchaseDetail );

    }
}
